package com.miaoshare.core.utils.imageLoad;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

/**
 * Created by sunfusheng on 16/4/6.
 */
public class GlideSquareRoundTransform extends BitmapTransformation {

    private static float radiusInPx = 0f;

    public GlideSquareRoundTransform(Context context) {
        this(context, 4);
    }

    public GlideSquareRoundTransform(Context context, int radiusInPx) {
//        super(context);
        this.radiusInPx = radiusInPx;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        int width = source.getWidth();
        int height = source.getHeight();
        float left, right, top, bottom;
        if (width > height) {
            left = (width - height)/2;
            right = left + height;
            top = 0;
            bottom = top + height;
        } else {
            left = 0;
            right = left + width;
            top = (height - width)/2;
            bottom = top + width;
        }
        RectF rectF = new RectF(left, top, right, bottom);
        canvas.drawRoundRect(rectF, radiusInPx, radiusInPx, paint);
        return result;
    }
    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {

    }
}
